import {CefQueryCfg} from "./CefQueryCfg";
import {CefKey} from "./CefKey.Const";
export interface ErrorRes {
    errorCode: number;
    errorMessage: string;
}

export const sendCefQuery = (
    cfg: CefQueryCfg,
    onSuccess?: (response: string) => void,
    onFailure?: (errorCode: number, errorMsg: string) => void
): void => {
    if ((window as any).cefQuery === undefined && cfg.key === CefKey.DATASOURCE && cfg.data.method === 'get') {
        onSuccess?.(JSON.stringify({
            body: [{id: '1', name: 'datasource1', path: '数据源1'}, {
                id: '2',
                name: 'datasource2',
                path: '数据源2'
            }]
        }));
        return;
    }
    if ((window as any).cefQuery === undefined && cfg.key === CefKey.SQL_STATEMENT && cfg.data.method === 'get') {
        onSuccess?.(JSON.stringify({
            body: [{id: 1, name: "test", sql: "test1"}]
        }));
        return;
    }
    (window as any).cefQuery?.({
        request: JSON.stringify({
            key: cfg.key,
            data: cfg.data,
        }),
        onSuccess: function (response: string) {
            onSuccess?.(response);
        },
        onFailure: function (errorCode: number, errorMsg: string) {
            onFailure?.(errorCode, errorMsg);
        }
    });
}

export const axiosCefQuery = (cef: CefQueryCfg): Promise<string> => {
    return new Promise((resolve, reject) => {
        const  onSuccess = (response: string): void =>{
            resolve(response);
        }
        const onFailure = (errorCode: number, errorMessage:string):void =>{
            const errorData: ErrorRes = {errorCode,errorMessage};
            reject(errorData);
        };
        sendCefQuery(cef, onSuccess,onFailure);
    });
}